package org.developer.server.rpc;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ServerController {

    //identifier 为注解 RemoteClass 中的 value值
    @RequestMapping("/")
    public Result rpcMain(String identifier,String methodName,String argTypes, String argValues){
        try{
            Class clazz = Class.forName(identifier);
            if (clazz == null) {
                return Result.getFailResult("目标类不存在");
            }

            //获取参数的类型，类型为String
            List<String> argTypeList = JSON.parseArray(argTypes, String.class);
            List<Class> argClassList = new ArrayList<>();
            for (String argType : argTypeList) {
                //通过反射获取到class对象
                argClassList.add(Class.forName(argType));
            }
            //保存到Class数组中
            Class[] argClassArray = new Class[argClassList.size()];
            argClassList.toArray(argClassArray);

            //获取参数值，且每个值为String类型
            List<String> argValueStringList = JSON.parseArray(argValues, String.class);
            List<Object> argValueList = new ArrayList<>();
            for (int i = 0; i < argTypeList.size(); i++) {
                if (argClassList.get(i).equals(String.class)) {
                    argValueList.add(argValueStringList.get(i));
                } else {
                    argValueList.add(JSON.parseObject(argValueStringList.get(i), argClassList.get(i)));
                }
            }
            //参数值列表
            Object[] args = new Object[argValueList.size()];
            argValueList.toArray(args);

            //查找 Server端 是否存在该方法
            Method method = clazz.getMethod(methodName, argClassArray);
            if (method == null) {
                return Result.getFailResult("目标方法不存在");
            }

            //获取实例
            Object obj = ServiceGetter.getServiceByClazz(clazz);
            if (obj == null) {
                return Result.getFailResult("目标类的实例无法生成");
            }
            //反射调用该方法
            Object result = method.invoke(obj, args);
            return Result.getSuccessResult(method.getReturnType().getName(), JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.getFailResult("服务端解析异常");
        }
    }
}
